package com.xiaoma.common.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import androidx.viewbinding.ViewBinding

/**
 * author: liangjingbo
 * date: 2022/6/27
 * describe:BaseAdapter
 */
abstract class XmBaseBindingAdapter<T, VB : ViewBinding>(
    private val inflate: (LayoutInflater, ViewGroup, Boolean) -> VB,
    data: MutableList<T> = mutableListOf()
) : XmBaseAdapter<T, XmBaseBindingAdapter.BaseBindingHolder<VB>>(data) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseBindingHolder<VB> {
        val root = inflate.invoke(LayoutInflater.from(parent.context), parent, false)
        return BaseBindingHolder(root)
    }

    override fun onBindViewHolder(holder: BaseBindingHolder<VB>, position: Int, payloads: MutableList<Any>) {
        if (payloads.isEmpty()) {
            onBindViewHolder(holder, position)
            return
        }
        convert(holder, mData[position], payloads)
    }

    override fun onBindViewHolder(holder: BaseBindingHolder<VB>, position: Int) {
        bindViewClickListener(holder)
        convert(holder, mData[position], position)
    }

    abstract fun convert(holder: BaseBindingHolder<VB>, data: T, position: Int)

    protected open fun convert(holder: BaseBindingHolder<VB>, data: T, payloads: List<Any>) {}

    class BaseBindingHolder<VB : ViewBinding>(val binding: VB) : RecyclerView.ViewHolder(binding.root)

}